package com.zjn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjn.pojo.Bill;
import com.zjn.pojo.Provider;
import com.zjn.pojo.User;
import com.zjn.service.BillService;
import com.zjn.service.ProviderService;
import com.alibaba.fastjson.JSONArray;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bill")
public class BillController {

    @Autowired
    private BillService billService;

    @Autowired
    private ProviderService providerService;

    /*实现订单列表页面*/
    @GetMapping("/list")
    public ModelAndView billList(@RequestParam(required = false, defaultValue = "1", value = "pageNum") Integer pageNum,
                                 @RequestParam(defaultValue = "8", value = "pageSize") Integer pageSize,
                                 HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        //为了程序的严谨性，判断非空：
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;   //设置默认当前页
        }
        if (pageSize == null) {
            pageSize = 5;    //设置默认每页显示的数据数
        }

        //从前端获取参数
        String productName = request.getParameter("queryPN");
        String providerId = request.getParameter("queryPI");
        String isPay = request.getParameter("queryIsPay");
        if (productName == "") {
            productName = null;
        }
        if (providerId == null) {
            providerId = "0";
        }
        if (isPay == null) {
            isPay = "0";
        }

        //将查询需要的参数存入map中
        Map<String, Object> map = new HashMap<>();
        map.put("productName", productName);
        map.put("providerId", Integer.parseInt(providerId));
        map.put("isPayment", Integer.parseInt(isPay));

        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);

        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<Bill> billList = billService.getBillList(map);
            //为每个对象查出对应的供应商名
            for (Bill bill : billList) {
                Provider provider = new Provider();
                provider.setId(bill.getProviderId());
                String proName = providerService.queryProByProvider(provider).getProName();
                bill.setProviderName(proName);
            }
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<Bill> pageInfo = new PageInfo<Bill>(billList, pageSize);

            //4.使用modelAndView将数据带回前端
            mav.addObject("pageInfo", pageInfo);
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }
        //获取供应商列表并传入前端
        map.put("proCode", null);
        map.put("proName", null);
        List<Provider> proList = providerService.getProList(map);
        mav.addObject("proList", proList);

        //将查询表中的参数返回，以增加用户的体验性
        mav.addObject("queryPN", productName);
        mav.addObject("queryPI", Integer.parseInt(providerId));
        mav.addObject("queryIsPay", Integer.parseInt(isPay));

        mav.setViewName("bill/BillList");
        return mav;
    }

    /*跳转到订单添加界面*/
    @GetMapping("/billAdd")
    public String toBillAdd() {
        return "bill/BillAdd";
    }

    /*实现订单添加*/
    @PostMapping(value = "/billAdd", produces = "application/json; charset=utf-8")
    public ModelAndView billAdd(Bill bill, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
        User currentUser = (User) subject.getPrincipal();
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add") && method != null) {
            bill.setCreationDate(new Date());
            bill.setCreatedBy(currentUser.getId());
            int flag = 0;
            flag = billService.billAdd(bill);
            if (flag > 0) {
                mav.setViewName("redirect:/bill/list");
            } else {
                mav.setViewName("bill/BillAdd");
            }
        }
        //ajax动态获取供应商栏参数
        else if (method.equals("getproviderlist") && method != null) {
            List<Provider> providerList = providerService.getProListNoLimit(new HashMap<String, Object>());
            try {
                //将roleList转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(providerList));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证登录账号billCode是否已经存在
        else if (method.equals("bcexist") && method != null) {
            //判断订单编码是否可用
            String billCode = request.getParameter("billCode");
            //用于存放对billCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断billCode是否为空
            if (StringUtils.isEmpty(billCode) || billCode == "") {
                resultMap.put("billCode", "empty");
            } else {
                Bill bill1 = new Bill();
                bill1.setBillCode(billCode);
                bill1 = billService.queryBillById(bill1);
                if (null != bill1) {
                    resultMap.put("billCode", "exist");
                } else {
                    resultMap.put("billCode", "notexist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*订单查看详情*/
    @RequestMapping("/billView/{id}")
    public ModelAndView BillView(@PathVariable("id") int billId) {
        ModelAndView mav = new ModelAndView();
        Bill bill = new Bill();
        //根据id查询出当前选中的供应商
        bill.setId(billId);
        bill = billService.queryBillById(bill);
        Provider provider = new Provider();
        provider.setId(bill.getProviderId());
        bill.setProviderName((providerService.queryProByProvider(provider)).getProName());
        //将数据传入前端
        mav.addObject("bill", bill);
        mav.setViewName("bill/BillView");
        return mav;
    }

    /*跳转到供应商修改页面*/
    @GetMapping("/billUpdate/{id}")
    public ModelAndView toBillModify(@PathVariable("id") int billId) {
        ModelAndView mav = new ModelAndView();
        Bill bill = new Bill();
        //根据id查询出当前选中的供应商
        bill.setId(billId);
        bill = billService.queryBillById(bill);
        //将数据传入前端
        mav.addObject("bill", bill);
        mav.setViewName("bill/BillUpdate");
        return mav;
    }

    /*订单修改*/
    @RequestMapping("/billUpdate")
    public ModelAndView BillModify(Bill bill, HttpServletRequest req) {
        ModelAndView mav = new ModelAndView();
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
        User currentUser = (User) subject.getPrincipal();
        //因为code设置为readonly，所以要将其手动注入对象属性中
        bill.setBillCode(req.getParameter("billCode"));
        //将修改者和修改时间注入对象属性中
        bill.setModifyBy(currentUser.getId());
        bill.setModifyDate(new Date());
        int flag = billService.modifyBillById(bill);
        if (flag > 0) {
            mav.setViewName("redirect:/bill/list");
        } else {
            mav.setViewName("redirect:/bill/billUpdate/" + bill.getId());
        }
        return mav;
    }

    /*删除员工*/
    @GetMapping("/billDelete")
    public ModelAndView billDelete(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String id = request.getParameter("code");
        Map<String, String> resultMap = new HashMap<String, String>();
        int flag = billService.deleteBillById(Integer.parseInt(id));
        if (flag > 0) {
//            mav.setViewName("redirect:/user/list");
            resultMap.put("code", "success");
        } else {
//            mav.setViewName("redirect:/user/list");
            resultMap.put("code", "error");
        }
        try {
            //把resultMap转为json字符串以json的形式输出
            //配置上下文的输出类型
            response.setContentType("application/json");
            //从response对象中获取往外输出的writer对象
            PrintWriter outPrintWriter = response.getWriter();
            //把resultMap转为json字符串 输出
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();//刷新
            outPrintWriter.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
        mav.setViewName("redirect:/bill/list");
        return mav;
    }
}
